package com.gitbl.webchat.roomnode;

import com.alibaba.fastjson.JSONObject;
import com.gitbl.webchat.message.RoomMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RestControl {

    Map<String, RestHandler> handlerMap;

    void regist(String method,String url,RestHandler handler){
        handlerMap.put(method+"_"+url,handler);
    }
    public RestControl(){
        handlerMap = new HashMap<>();
        //构建路由字典
        //这里如果方法多了可以剥离出来定义多个handler
        regist("POST", "/create", new RestHandler() {
            @Override
            public byte[] request(ChannelHandlerContext ctx, FullHttpRequest req) {

                byte[] buffer = new byte[Integer.parseInt(req.headers().get("Content-Length"))];
                req.content().readBytes(buffer);

                String postdata = new String(buffer);
                QueryStringDecoder queryDecoder = new QueryStringDecoder(postdata, false);
                Map<String, List<String>> uriAttributes = queryDecoder.parameters();

                if(uriAttributes==null||(!uriAttributes.containsKey("title"))||(!uriAttributes.containsKey("owner"))){
                    return new byte[0];
                }
                String title = uriAttributes.get("title").get(0);
                String owner = uriAttributes.get("owner").get(0);
                RoomMessage room = RoomsNode.instance().createRoom(title,owner);
                RoomsNode.instance().updateOne(room);
                byte[] content = JSONObject.toJSONBytes(room);
                return content;
            }
        });

    }

    RestHandler router( FullHttpRequest req){
        String key = req.method().name()+"_"+req.uri();
        if(handlerMap.containsKey(key)){
            return handlerMap.get(key);
        }
        return null;
    }


    public byte[] request(ChannelHandlerContext ctx, FullHttpRequest req) {
        RestHandler h = router(req);
        if(h==null){
            return null;
        }
        return h.request(ctx,req);
    }
}
